﻿using Newtonsoft.Json.Serialization;
using Owin;
using Swashbuckle.Application;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.Http.Formatting;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Cors;

namespace Lails.Server
{
    public class WebAPIConfig
    {
        private HttpConfiguration _config;
        public HttpConfiguration CurrentConfiguration
        {
            get { return _config; }
        }

        public void Configuration(IAppBuilder app)
        {
            var config = ConfigureApi();
            app.UseStaticFiles();
            app.UseWebApi(config);
        }

        private HttpConfiguration ConfigureApi()
        {
            _config = new HttpConfiguration();

            _config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new DefaultContractResolver() { IgnoreSerializableAttribute = true };
            _config.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
            _config.Formatters.JsonFormatter.MediaTypeMappings.Add(new QueryStringMapping("datatype", "json", "application/json"));
            _config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(
                new Newtonsoft.Json.Converters.IsoDateTimeConverter()
                {
                    DateTimeFormat = "yyyy-MM-dd HH:mm:ss"
                }
            );

            //Swagger配置
            var name = Process.GetCurrentProcess().ProcessName;
            _config.EnableSwagger(c =>
            {
                c.SingleApiVersion("v1", $"{name}的API文档");
                c.IncludeXmlComments($@"{AppDomain.CurrentDomain.BaseDirectory}\{name}.XML");
            }).EnableSwaggerUi();

            //跨域配置
            _config.EnableCors(new EnableCorsAttribute("*", "*", "*"));
            _config.Routes.MapHttpRoute(
                "DefaultApi",
                "{controller}/{action}/{id}",
                new { id = RouteParameter.Optional });

            _config.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
            AutofacConfig.Initialize(_config);
            return _config;
        }
    }
}
